package com.example.administrator.mybabymall.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import com.example.administrator.mybabymall.Contants;
import com.example.administrator.mybabymall.R;
import com.example.administrator.mybabymall.adapter.HomeCatgoryAdapter;
import com.example.administrator.mybabymall.bean.Banner;
import com.example.administrator.mybabymall.bean.Campaign;
import com.example.administrator.mybabymall.bean.HomeCampaign;
import com.example.administrator.mybabymall.util.DivideItemDecoration;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;

/**
 * Created by Administrator on 2017/12/22 0022.
 */

public class FragmentOne extends Fragment {
    private SliderLayout sliderLayout;
    private PagerIndicator pagerIndicator;
    private Gson gson = new Gson();
    private List<Banner> mbanners = new ArrayList<>();
    List<HomeCampaign> homeCampaigns = new ArrayList<>();
    private RecyclerView recyclerView;
    private HomeCatgoryAdapter homeCatgoryAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_one, container, false);

//        绑定轮播图
        sliderLayout = view.findViewById(R.id.slider);
//        绑定轮播图标识点
        pagerIndicator = view.findViewById(R.id.custom_indicator);
//        绑定recyclerView
        recyclerView = view.findViewById(R.id.recyclerview_home);
//        OKHttp请求，获取轮播图Json
        outputJson(Contants.API.SLIDER_HOME,1);
//        OKHttp请求，获取首页商品Json
        outputJson(Contants.API.CAMPAIGN_HOME,2);

        return view;
    }

    //    首页商品布局及设置
    private void initRecyclerView(List<HomeCampaign> datas) {

        if(datas != null){
//        获取Adapter实例，并传入数据
            homeCatgoryAdapter = new HomeCatgoryAdapter(datas,getActivity());
            homeCatgoryAdapter.setOnCampaignClickListener(new HomeCatgoryAdapter.OnCampaignClickListener() {
                @Override
                public void onClick(View viewl, Campaign campaign) {
                    Toast.makeText(getContext(),campaign.getTitle(),Toast.LENGTH_SHORT).show();

                }
            });
//        设置Adapter
            recyclerView.setAdapter(homeCatgoryAdapter);
//        设置中间垂直间隔
            recyclerView.addItemDecoration(new DivideItemDecoration());
//        设置布局样式
            recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
        }
    }

    private void initSlider() {

        if(mbanners != null){
            for(final Banner banner :mbanners){

                TextSliderView textSliderView = new TextSliderView(this.getActivity());
                textSliderView
                        .description(banner.getName())
                        .image(banner.getImgUrl());
                sliderLayout.addSlider(textSliderView);

                textSliderView.setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
                    @Override
                    public void onSliderClick(BaseSliderView slider) {
                        Toast.makeText(FragmentOne.this.getActivity(), banner.getName(), Toast.LENGTH_SHORT).show();

                    }
                });
            }
        }
//        设置图片，按说明来就行
//        TextSliderView textSliderView = new TextSliderView(this.getActivity());
//        textSliderView
//                .description("性感花边")
//                .image("http://www.taopic.com/uploads/allimg/140107/234764-14010F0310582.jpg");

//        轮播图的监听
//        textSliderView.setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
//            @Override
//            public void onSliderClick(BaseSliderView slider) {
//                Toast.makeText(HomeFragment.this.getActivity(), "性感花边", Toast.LENGTH_SHORT).show();
//
//            }
//        });

//        添加图片，有几个添加几个
//        sliderLayout.addSlider(textSliderView);
//        sliderLayout.addSlider(textSliderView2);

//        图片轮播效果设置

//        默认点
//        sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
//        自定义小点
        sliderLayout.setCustomIndicator(pagerIndicator);
//        图片的下面一栏自动隐藏
        sliderLayout.setCustomAnimation(new DescriptionAnimation());
//        轮播动画的样式
        sliderLayout.setPresetTransformer(SliderLayout.Transformer.DepthPage);
//        轮播跳转间隔
        sliderLayout.setDuration(5000);


//        轮播状态的控制
        sliderLayout.addOnPageChangeListener(new ViewPagerEx.OnPageChangeListener() {

            //            滚动过程中会不停调用本方法
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                Log.v("now", "onPageScrolled" + position);
            }

            //            处于当前状态的图片调用，只调用一次,开始滑动调用
            @Override
            public void onPageSelected(int position) {
//                Log.v("now", "onPageSelected-----" + position);

            }

            //            图片改变过后，或调用一次，但不一定，滑动结束调用
            @Override
            public void onPageScrollStateChanged(int position) {
//                Log.v("now", "onPageScrollStateChanged" + position);

            }
        });
    }

    //    OKhttp获取URL  Json数据
    private  void outputJson(String url, final int num) {

        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.e("OKHTTP:", "ERROR");
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    String str = response.body().string();
//                    Log.v("OKHTTP:", "json:" + str);
                    Message message = Message.obtain();
                    message.what = num;
                    message.obj = str;
                    handler.sendMessage(message);
                } else {
                    Log.v("Response", "访问失败");
                }

            }

        });

    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 1){
//              接收异步OKHTTP传来的Slider数据
                String result = (String) msg.obj;
//              使用Gson将字符串转化为ArrayList对象
                Type type = new TypeToken<List<Banner>>() {}.getType();
                mbanners = gson.fromJson(result,type);
//              调用轮播图显示
                initSlider();
            }else if (msg.what == 2){
                String result = (String)msg.obj;
                Type type = new TypeToken<List<HomeCampaign>>() {}.getType();
                homeCampaigns = gson.fromJson(result,type);
                initRecyclerView(homeCampaigns);
            }

        }
    };
}
